﻿using System;
using System.IO;
using System.Text;

namespace VCards.Helpers;

public static class FileHelper
{
    public static string[] ReadVCardString(string path)
    {
        if (!File.Exists(path))
        {
            return Array.Empty<string>();
        }

        using var sr = File.OpenText(path);
        var builder = new StringBuilder();

        string line;
        bool isPhoto = false;
        while ((line = sr.ReadLine()) != null)
        {
            // V2.1有换行的情况
            if (line.EndsWith('='))
            {
                builder.Append(line.AsSpan(0, line.Length - 1));
                continue;
            }
            // 内置图片编码
            if (isPhoto)
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    isPhoto = false;
                    builder.Append(Environment.NewLine);
                }
                else
                {
                    builder.Append(line.AsSpan(1));
                }
                continue;
            }
            if (line.StartsWith("PHOTO;"))
            {
                isPhoto = true;
                builder.Append(line);
                continue;
            }
            builder.Append(line);
            builder.Append(Environment.NewLine);
        }

        string contents = builder.ToString();
        return VCardHelper.SplitCards(contents);
    }
}